//
//  HttpConnctionManager.m
//  hellomui
//
//  Created by zhangtao on 15/9/30.
//  Copyright © 2015年 zt.td. All rights reserved.
//

#import "HttpConnctionManager.h"

#import "HttpConnctionManager.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPSessionManager.h"
#import "AFURLRequestSerialization.h"
#import "JSONKit.h"

@implementation HttpConnctionManager

//- (void)dealloc
//{
//    [super dealloc];
//}

- (id)init
{
    self = [super initWithBaseURL:[NSURL URLWithString:S_SERVER]];
    if(self)
    {
        self.responseSerializer = [AFHTTPResponseSerializer serializer];
        //并发线程数
        [self.operationQueue setMaxConcurrentOperationCount:5];
        AFHTTPRequestSerializer * serial = [[AFHTTPRequestSerializer alloc]init];
//        [serial setValue:@"application/json"  forHTTPHeaderField:@"Accept"];
//        [serial setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField: @"Content-type"];
        [self setRequestSerializer:serial];
        
        AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
        
        [self setResponseSerializer:responseSerializer];
    }
    return self;
}

SINGLETON_FOR_CLASS(HttpConnctionManager)


#pragma mark - 封装过的网络请求接口

- (void)startGetWith:( NSString *)url
            paragram:(NSDictionary *)para
      successedBlock:(SuccessedBlock)success
         failedBolck:(FailedBlock)failed
{
    AFHTTPRequestOperation *  operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    [operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if(success)
         {
             id res  = [operation.responseString objectFromJSONString];
             success((NSDictionary *)res);
         }
     }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if (failed)
         {
             failed(operation, error);
         }
     }
     ];
    [operation start];
}

//普通的post请求
- (void)startNormalPostWith:( NSString *)url
                   paragram:(NSDictionary *)para
             successedBlock:(SuccessedBlock)success
                failedBolck:(FailedBlock)failed
{
    
    [self POST:url
    parameters:para
       success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"hehehehehhe::operation:%@",operation);
         
         //             if([[responseObject objectForKey:@"result"]integerValue] == KEY_VALUE_TOKEN_OUTDATE)
         //             {
         //                 [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:KEY_IS_OUTDEATE_TOKEN];
         //                 [PubllicMaskViewHelper showMaskViewIn:@"用户身份失效,自动重新登录"];
         //                 [self performSelector:@selector(logoutForTokenOutdate) withObject:nil afterDelay:1];
         //                 return ;
         //             }
         NSLog(@"responseObject=%@", responseObject);
         NSLog(@"%@", [responseObject objectForKey:@"state"]);
         success(responseObject);
     }
       failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {

         failed(operation,error);
     }
     ];
}


/////
//普通的GET请求__back->array    __zt
- (void)startNormalGetWith:( NSString *)url
                   paragram:(NSDictionary *)para
             successedBlock:(SuccessedArrayBlock)success
                failedBolck:(FailedBlock)failed
{
    
    [self GET:url
    parameters:para
       success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         
         //             if([[responseObject objectForKey:@"result"]integerValue] == KEY_VALUE_TOKEN_OUTDATE)
         //             {
         //                 [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:KEY_IS_OUTDEATE_TOKEN];
         //                 [PubllicMaskViewHelper showMaskViewIn:@"用户身份失效,自动重新登录"];
         //                 [self performSelector:@selector(logoutForTokenOutdate) withObject:nil afterDelay:1];
         //                 return ;
         //             }
         NSLog(@"responseObject=%@", responseObject);
         NSLog(@"%@", [responseObject objectForKey:@"state"]);
         success(responseObject);
         
     }
       failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         
         failed(operation,error);
     }
     ];
}


-(void)PostRequestParam:(NSDictionary *)dic andUrl:(NSString *)url andSuccessedArrayBlock:(SuccessedArrayBlock)success andFailedBlock:(FailedBlock)failed{
    [self POST:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        success(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failed(operation,error);

    }];
    
    
}


//上传file类型的post请求
- (void)startMulitDataPost:( NSString *)url
                  postFile:(NSData *)uploadFileData
                  paragram:(NSDictionary *)para
            successedBlock:(SuccessedBlock)success
               failedBolck:(FailedBlock)failed
{
    [self POST:url
    parameters:para
constructingBodyWithBlock:^(id <AFMultipartFormData> formData)
     {
         if(uploadFileData)
         {
             [formData appendPartWithFileData:uploadFileData name:@"fileupload" fileName:@"pic.jpg" mimeType:@"image/jpg"];
         }
     }
       success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if(success)
         {
             id res  = [operation.responseString objectFromJSONString];
             //                             SpeAssert([res isKindOfClass:[NSDictionary class]]);
             success((NSDictionary *)res);
         }
     }
       failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if (failed)
         {
             failed(nil, error);
         }
     }
     ];
}

#pragma mark - 所有的公用接口
//用户登录
- (void)startLogin:(NSString *)username andPassword:(NSString *)password andSuccessedBlock:(SuccessedBlock)success andFailedBlock:(FailedBlock)failed
{
    NSDictionary *reqDic = @{
                             @"userName":username,
                             @"password":password
                             };
    [self startNormalPostWith:@"UserRTS/login" paragram:reqDic successedBlock:success failedBolck:failed];
}

// ---- zt
-(void)requestParam:(NSDictionary *)dic andUrl:(NSString *)url andSuccessedBlock:(SuccessedBlock)success andFailedBlock:(FailedBlock)failed{
    [self startNormalPostWith:url paragram:dic successedBlock:success failedBolck:failed];
}

-(void)postURl:(NSString *)url fileData:(NSData *)data param:(NSDictionary *)dic andSuccessedBlock:(SuccessedBlock)success andFailedBlock:(FailedBlock)failed{
    [self startMulitDataPost:url postFile:data paragram:dic successedBlock:success failedBolck:failed];
}

-(void)GetRequestParam:(NSDictionary *)dic andUrl:(NSString *)url andSuccessedArrayBlock:(SuccessedArrayBlock)success andFailedBlock:(FailedBlock)failed{
    
    [self startNormalGetWith:url paragram:dic successedBlock:success failedBolck:failed];
}


//-(void)GetRequestParam:(NSDictionary *)dic andUrl:(NSString *)url andSuccessedBlock:(SuccessedBlock)success andFailedBlock:(FailedBlock)failed{
//    [self sta]
//}


@end
